<template>
  {{ queryForm }}
  <div class="user-view-page">
    <el-card class="search-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>用户查询</span>
        </div>
      </template>
      <el-form :model="queryForm" :inline="true" class="search-form">
        <el-form-item label="账号/姓名">
          <el-input v-model="queryForm.name" placeholder="请输入账号或姓名" clearable style="width: 200px"
            @keyup.enter="handleSearch" />
        </el-form-item>

        <el-form-item label="组织">

          <el-cascader v-model="queryForm.zid" :options="organOptions" :props="props" @change="handleChange" />
        </el-form-item>

        <el-form-item label="状态">
          <el-select v-model="queryForm.status" placeholder="请选择状态" clearable style="width: 150px">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">
            查询
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>用户列表</span>
          <el-button type="primary" link @click="fetchUserList" :loading="loading">
            刷新
          </el-button>
        </div>
      </template>
      <el-button type="success" style="margin: 12px;" @click="Open('')">新增</el-button>
      <el-button type="danger" style="margin: 12px;" :disabled="selectedUsers.length === 0" @click="handleBatchDelete">
        批量删除 ({{ selectedUsers.length }})
      </el-button>
      <el-table v-loading="loading" :data="userList" border stripe style="width: 100%" :height="500"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="usernumber" label="工号" width="120" align="center" />
        <el-table-column prop="username" label="用户姓名" width="120" align="center" />
        <el-table-column prop="accountname" label="账号" width="150" align="center" />
        <el-table-column prop="usersex" label="性别" width="80" align="center" />
        <el-table-column prop="phone" label="手机号" width="130" align="center" />
        <el-table-column prop="emails" label="邮箱" width="180" align="center" />
        <el-table-column prop="organname" label="组织" width="150" align="center" />
        <el-table-column prop="jobname" label="岗位" width="120" align="center" />
        <el-table-column prop="rolename" label="角色" width="120" align="center" />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right" align="center">
          <template #default="{ row }">
            <el-button type="primary" size="small" link @click="Open(row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" link @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination v-model:current-page="pagination.pageindex" v-model:page-size="pagination.pagesize"
          :page-sizes="[10, 20, 50, 100]" :total="pagination.totalCount"
          layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </el-card>
  </div>

  <el-dialog draggable v-model="logic.IsOpen" :title="logic.Title" width="500">
    <el-form :label-width="120">
      {{ models }}
      <el-form-item label="用户姓名">
        <el-input v-model="models.username" />
      </el-form-item>
      <el-form-item label="工号">
        <el-input v-model="models.usernumber" />
      </el-form-item>
      <el-form-item label="用户名">
        <el-input v-model="models.accountname" />
      </el-form-item>
      <el-form-item label="密码">
        <el-input show-password v-model="models.pwd" />
      </el-form-item>
      <el-form-item label="性别">
        <el-input v-model="models.usersex" />
      </el-form-item>
      <el-form-item label="组织">

        <el-cascader v-model="models.organid" :options="organOptions" :props="props" @change="handleChange"
          style="width: 350px;" />
      </el-form-item>
      <el-form-item label="岗位">
        <el-select placeholder="请选择" v-model="models.jobid">
          <el-option v-for="item in arrjob" :label="item.jobname" :value="item.id" />

        </el-select>
      </el-form-item>
      <el-form-item label="手机号">
        <el-input v-model="models.phone" />
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="models.emails" />
      </el-form-item>
      <el-form-item label="角色">
        <el-select placeholder="请选择" v-model="models.roleid">
          <el-option v-for="item in arrrle" :label="item.rolename" :value="item.id" />

        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-radio-group v-model="models.status">
          <el-radio :value="1">启用</el-radio>
          <el-radio :value="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>

    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="logic.IsOpen = false">取消</el-button>
        <el-button type="primary" @click="AddUser">
          完成
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import https from "@/Http/http";
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from "element-plus";

interface UserDto {
  id: number
  username: string
  usernumber: string
  accountname: string
  usersex: string
  phone: string
  emails: string
  status: number
  roleid: number
  rolename: string
  organid: number
  organname: string
  jobid: number
  jobname: string
}

interface BindDto {
  value: number
  label: string
  children?: BindDto[]
}

interface QueryForm {
  name?: string
  zid?: number
  status?: number
}

interface Pagination {
  pageindex: number
  pagesize: number
  totalCount: number
  pageCount: number
}


const loading = ref(false)
const userList = ref<UserDto[]>([])
const organOptions = ref<BindDto[]>([])
const selectedUsers = ref<UserDto[]>([])

const hh: any = ref(null);
const handleChange = (value: any) => {
  console.log(value)
  hh.value = value[value.length - 1]
}

const queryForm = reactive<QueryForm>({
  name: '',
  zid: hh,
  status: undefined
})

const pagination = reactive<Pagination>({
  pageindex: 1,
  pagesize: 10,
  totalCount: 0,
  pageCount: 0
})

const getStatusCode = (payload: any) => payload?.code ?? payload?.Code
const getPayloadData = <T,>(payload: any): T => payload?.data ?? payload?.Data
const getPayloadMsg = (payload: any): string => payload?.msg ?? payload?.Msg ?? ''

// 获取组织下拉列表
const fetchOrganOptions = async () => {
  https.Reads.get("/Organtion/Binds")
    .then(res => {
      console.log(res);
      if (res.data.code == 1) {
        organOptions.value = res.data.data;
      }
    })
}

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true
  try {
    const params: any = {
      pageindex: pagination.pageindex,
      pagesize: pagination.pagesize
    }

    if (queryForm.name) {
      params.name = queryForm.name
    }
    if (queryForm.zid) {
      params.zid = queryForm.zid
    }
    if (queryForm.status !== undefined && queryForm.status !== null) {
      params.status = queryForm.status
    }

    const { data } = await https.Reads.get(`/RBAC/ShowUser`, { params })

    if (getStatusCode(data) === 1) {
      // ApiPageing格式: { Code, Msg, TotalCount, PageCount, Data }
      userList.value = data.Data || data.data || []
      pagination.totalCount = data.TotalCount || data.totalCount || 0
      pagination.pageCount = data.PageCount || data.pageCount || 0
    } else {
      ElMessage.error(getPayloadMsg(data) || '获取用户列表失败')
      userList.value = []
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('无法获取用户列表，请检查服务是否可用')
    userList.value = []
  } finally {
    loading.value = false
  }
}
const defaultProps = {
  children: 'children',
  label: 'label',
  value: ''
}
const props = {
  expandTrigger: 'hover' as const,
}
// 查询
const handleSearch = () => {
  pagination.pageindex = 1
  fetchUserList()
}

// 重置
const handleReset = () => {
  queryForm.name = ''
  queryForm.zid = undefined
  queryForm.status = undefined
  pagination.pageindex = 1
  fetchUserList()
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.pagesize = val
  pagination.pageindex = 1
  fetchUserList()
}

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.pageindex = val
  fetchUserList()
}

// 编辑
const handleEdit = (row: UserDto) => {
  ElMessage.info(`编辑用户: ${row.username} (功能待实现)`)
  // TODO: 实现编辑功能
}

// 表格选择变化
const handleSelectionChange = (selection: UserDto[]) => {
  selectedUsers.value = selection
}

// 删除
const handleDelete = async (row: UserDto) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户「${row.username}」吗？`,
      '提示',
      {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }
    )

    // 调用单个删除接口
    await deleteUsers([row.id])
  } catch {
    // 用户取消删除
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedUsers.value.length === 0) {
    ElMessage.warning('请先选择要删除的用户')
    return
  }

  try {
    const userNames = selectedUsers.value.map(u => u.username).join('、')
    await ElMessageBox.confirm(
      `确定要删除以下 ${selectedUsers.value.length} 个用户吗？\n${userNames}`,
      '批量删除确认',
      {
        type: 'warning',
        confirmButtonText: '确定删除',
        cancelButtonText: '取消'
      }
    )

    const ids = selectedUsers.value.map(u => u.id)
    await deleteUsers(ids)
  } catch {
    // 用户取消删除
  }
}

// 执行删除操作
const deleteUsers = async (ids: number[]) => {
  try {
    const { data } = await https.Writes.delete('/RBAC/DelAll', {
      data: { ids: ids }
    })

    if (data.code === 1 || data.Code === 1) {
      const count = data.data || data.Data || ids.length
      ElMessage.success(`成功删除 ${count} 个用户`)
      // 清空选中项
      selectedUsers.value = []
      // 刷新列表
      fetchUserList()
    } else {
      ElMessage.error(data.msg || data.Msg || '删除失败')
    }
  } catch (error: any) {
    console.error('删除失败:', error)
    ElMessage.error(error.response?.data?.msg || error.message || '删除失败，请稍后重试')
  }
}

//绑定角色
const arrrle: any = ref([]);
const showrole = () => {
  https.Reads.get("/RBAC/ShowRole")
    .then(res => {
      console.log(res);
      arrrle.value = res.data.data;
    })
}
//绑定岗位
const arrjob: any = ref([]);
const showjob = () => {
  https.Reads({
    url: "/RBAC/ShowJob",
    method: "get",
  })
    .then(res => {
      console.log(res);
      arrjob.value = res.data.data;
    })
}
//新增
const models: any = reactive({
  id:null,
  "username": "",
  "usernumber": "",
  "accountname": "",
  "usersex": "",
  "phone": "",
  "pwd": "",
  "emails": "",
  "status": null,
  "roleid": null,
  "organid": hh,
  "jobid": null
})

const logic: any = reactive({
  IsOpen: false,
  Title: "",
  IsAdd: false
})
//打开对话框
const Open = (row: any) => {
  logic.IsOpen = true;
  if (row == '') {
    logic.Title = "新增";
    logic.IsAdd = true;
    models.id = null;
    models.username = "";
    models.usernumber = "";
    models.accountname = "";
    models.usersex = "";
    models.phone = "";
    models.pwd = "";
    models.emails = "";
    models.status = null;
models.roleid = null;
models.organid = null;
models.jobid = null;
  }
  else {
    logic.Title = "编辑";
    logic.IsAdd = false
    models.id = row.id;
    models.username = row.username;
    models.usernumber = row.usernumber;
    models.accountname = row.accountname;
    models.usersex = row.usersex;
    models.phone = row.phone;
    models.pwd = row.pwd;
    models.emails = row.emails;
    models.status = row.status;
models.roleid = row.roleid;
models.organid = row.organid;
models.jobid = row.jobid;
  }

}
const AddUser = () => {
  if (logic.IsAdd) {
    https.Writes.post("/RBAC/AddUser", models)
      .then(res => {
        console.log(res);
        if (res.data.code == 1) {
          ElMessage.success(res.data.msg);
          logic.IsOpen = false;
          fetchUserList();
        }
        else {
          ElMessage.error(res.data.msg);
        }
      })
  }
  else{
     https.Writes.put("/RBAC/UpdateUser", models)
      .then(res => {
        console.log(res);
        if (res.data.code == 1) {
          ElMessage.success(res.data.msg);
          logic.IsOpen = false;
          fetchUserList();

        }
        else {
          ElMessage.error(res.data.msg);
        }
      })
  }

}

onMounted(() => {
  fetchOrganOptions()
  fetchUserList()
  showrole()
  showjob()
})
</script>

<style scoped>
.user-view-page {
  padding: 20px;
  background: #f5f6f8;
  min-height: calc(100vh - 60px);
  box-sizing: border-box;
}

.search-card,
.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
}

.search-form {
  margin-top: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
